<template>
  <div class="homened_container">
    <el-form
      ref="elderFormRef"
      :model="form"
      style="height: 720px"
      :rules="rules"
      label-width="110px"
    >
      <el-scrollbar class="custom-scrollbar">
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="申请编号"
              prop="applyCode"
              style="font-weight: 700"
            >
              <el-input
                v-model="form.applyCode"
                placeholder="请输入申请编号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期" prop="applyDate">
              <el-input
                v-model="form.applyDate"
                placeholder="请输入申请日期"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="申请人姓名"
              prop="applyId"
              style="font-weight: 700"
            >
              <el-select
                v-model="form.applyId"
                clearable
                filterable
                placeholder="请选择申请人姓名"
                @change="changePeole"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in applyPeople"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                >
                  <span>{{ dict.nameAndIdCard }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="居住状况"
              prop="livingConditions"
              style="font-weight: 700"
            >
              <el-select
                v-model="form.livingConditions"
                clearable
                placeholder="请选择居住状况"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in living_conditions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="联系电话"
              prop="telephone"
              style="font-weight: 700"
            >
              <el-input v-model="form.telephone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select
                v-model="form.sex"
                clearable
                placeholder="请选择性别"
                disabled
                style="width: 100%"
              >
                <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号">
              <el-input
                v-model="form.idCard"
                placeholder="请输入身份证号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期">
              <el-input
                v-model="form.birthDate"
                :disabled="true"
                placeholder="请输入出生日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄">
              <el-input
                v-model="form.age"
                :disabled="true"
                placeholder="请输入年龄"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="家庭住址"
              prop="livingAddrProvinceId"
              style="font-weight: 700"
            >
              <el-select
                v-model="form.livingAddrProvinceId"
                placeholder="选择省"
                style="width: 130px"
                @change="changelivingProvince"
              >
                <el-option
                  v-for="dict in livingRegionList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.livingAddrCityId"
                placeholder="选择市"
                style="width: 130px; margin-left: 5px"
                @change="changelivingCity"
              >
                <el-option
                  v-for="dict in livingCityList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>
              <el-select
                v-model="form.livingAddrCountyId"
                placeholder="选择区/县"
                style="width: 130px; margin-left: 5px"
                @change="changelivingCounty"
              >
                <el-option
                  v-for="dict in livingCountyList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>

              <el-select
                v-model="form.livingAddrStreetId"
                placeholder="选择乡村街道"
                style="width: 150px; margin-left: 5px"
                @change="changelivingStreet"
              >
                <el-option
                  v-for="dict in livingStreetList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>

              <el-select
                v-model="form.livingAddrCommunityId"
                placeholder="选择乡村社区"
                style="width: 190px; margin-left: 5px"
                @change="changelivingCommunity"
              >
                <el-option
                  v-for="dict in livingAddrCommunity"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="家庭详细地址"
              prop="livingDetailAddress"
              style="font-weight: 700"
            >
              <el-input
                v-model="form.livingDetailAddress"
                placeholder="请输入家庭详细地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="代理人姓名"
              prop="agentName"
              style="font-weight: 700"
            >
              <el-input
                v-model="form.agentName"
                placeholder="请输入代理人姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="代理人电话"
              prop="agentTelephone"
              style="font-weight: 700"
            >
              <el-input
                v-model="form.agentTelephone"
                placeholder="请输入联系人电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="身份证正面照"
              prop="positiveUrl"
              style="font-weight: 700"
            >
              <el-upload
                limit="1"
                class="avatar-uploader"
                :action="url"
                :headers="upload.headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccessPositive"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="PositiveUrl"
                  :src="PositiveUrl"
                  class="avatar"
                  style="width: 280px; height: 180px"
                  fit="cover"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="身份证反面照"
              prop="negativeUrl"
              style="font-weight: 700"
            >
              <el-upload
                class="avatar-uploader"
                :action="url"
                :headers="upload.headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccessNegative"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="imageUrl"
                  :src="imageUrl"
                  class="avatar"
                  style="width: 280px; height: 180px"
                  fit="cover"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="householdRegisterUrl" style="font-weight: 700">
              <template #label>
                <div
                  class="custom-label"
                  style="line-height: 18px; font-weight: 700"
                >
                  户口本内页 （自己那页）
                </div>
              </template>
              <el-upload
                class="avatar-uploader"
                :action="url"
                :headers="upload.headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccessRegister"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="RegisterUrl"
                  :src="RegisterUrl"
                  class="avatar"
                  style="width: 280px; height: 180px"
                  fit="cover"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align: right; margin-top: 10px">
          <el-button type="warning" @click="submitFormDebounceHandler('1')"
            >提交审核</el-button
          >
          <el-button type="primary" @click="submitFormDebounceHandler('0')"
            >保存草稿</el-button
          >
          <el-button @click="cancel(false)">取 消</el-button>
        </div>
      </el-scrollbar>
    </el-form>

    <!-- 添加或修改岗位对话框 -->
  </div>
</template>

<script setup name="communitySite">
const { proxy } = getCurrentInstance();
const { sys_normal_disable, living_conditions, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "living_conditions",
  "sys_user_sex",
);
import moment from "moment";
import { getToken } from "@/utils/auth";
import {
  genApplyCode,
  listAll,
  homeBedApplySave,
  homeBedApplyUpdata,
} from "@/api/homebedsign/index";
import { elderArchiveinfo } from "@/api/record/api";
import { region } from "@/api/record/api";
import { debounce } from "@/utils/debounce.js";
const applyPeople = ref([]);
const regionList = ref([]);
const livingRegionList = ref([]);
const livingCityList = ref([]);
const livingCountyList = ref([]);
const livingStreetList = ref([]);
const livingAddrCommunity = ref([]);
const dialogVisible = ref(false);
const dialogImageUrl = ref("");
const imageUrl = ref("");
const RegisterUrl = ref("");
const disabled = ref(false);
const url = ref(
  process.env.VUE_APP_BASE_API + '/file/upload/pk-home-bed-apply',
)
const upload = reactive({
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
});
const PositiveUrl = ref("");
const { formData } = defineProps(["formData"]);
const emits = defineEmits("closed");
const data = reactive({
  form: {
    applyDate: moment().format("YYYY-MM-DD"),
  },

  rules: {
    applyCode: [{ required: true, message: "请输入申请编号", trigger: "blur" }],
    applyDate: [{ required: true, message: "请输入申请日期", trigger: "blur" }],
    applyId: [
      { required: true, message: "请选择申请人姓名", trigger: "change" },
    ],
    livingConditions: [
      { required: true, message: "请选择居住状况", trigger: "change" },
    ],
    telephone: [
      { required: true, message: "请输入正确手机号", trigger: "blur" },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    livingAddrProvinceId: [
      { required: true, message: "家庭住址不能为空", trigger: "change" },
    ],
    livingDetailAddress: [
      { required: true, message: "家庭详细地址不能为空", trigger: "blur" },
      {
        required: true,
        min: 1,
        max: 50,
        message: '常住详细地址不超过50个字符',
        trigger: 'blur',
      },
    ],
    agentName: [
      { required: true, message: "代理人姓名不能为空", trigger: "blur" },
      {
        required: true,
        min: 1,
        max: 10,
        message: '代理人姓名不超过10个字符',
        trigger: 'blur',
      },
    ],
    agentTelephone: [
      { required: true, message: "代理人电话不能为空", trigger: "blur" },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    positiveUrl: [
      { required: true, message: "身份证正面照不能为空", trigger: "blur" },
    ],
    negativeUrl: [
      { required: true, message: "身份证反面照不能为空", trigger: "blur" },
    ],
    householdRegisterUrl: [
      {
        required: true,
        message: "户口本内页 （自己那页不能为空）",
        trigger: "blur",
      },
    ],
  },
});

const { form, rules } = toRefs(data);

/** 提交按钮 */
const submitFormDebounceHandler = debounce((data) => submitForm(data), 500);

function submitForm(data) {
  form.value.applyStatus = data;
  proxy.$refs["elderFormRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        homeBedApplyUpdata(form.value).then((response) => {
          if (form.value.applyStatus === "0") {
            proxy.$modal.msgSuccess("存入草稿箱");
          }
          if (form.value.applyStatus === "1") {
            proxy.$modal.msgSuccess("提交申请成功");
          }

          cancel(true);
        })
      } else {
        homeBedApplySave(form.value).then((response) => {
          if (form.value.applyStatus === "0") {
            proxy.$modal.msgSuccess("存入草稿箱");
          }
          if (form.value.applyStatus === "1") {
            proxy.$modal.msgSuccess("提交申请成功");
          }
          cancel(true);
        })
      }
    }
  });
}

function handleAvatarSuccessPositive(file) {
  PositiveUrl.value = file.data.url;
  form.value.positiveUrl = file.data.url;
}
function handleAvatarSuccessNegative(file) {
  imageUrl.value = file.data.url;
  form.value.negativeUrl = file.data.url;
}
function handleAvatarSuccessRegister(file) {
  RegisterUrl.value = file.data.url;
  form.value.householdRegisterUrl = file.data.url;
}
function cancel(data) {
  proxy.resetForm("addevaluationItemRef");
  emits("closed", data);
}

function beforeAvatarUpload(file, fileFist) {
  // 校验图片格式是否合法
  const isLegal =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png';
  // 文件大小不超过2MB
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLegal) {
    // 文件格式是否合法
    proxy.$modal.msgError("上传头像图片只能是 JPG、JPEG、PNG 格式!");
  }

  if (!isLt2M) {
    // 图片大小超过2MB
    proxy.$modal.msgSuccess("上传头像图片大小不能超过 2MB!");
  }

  return isLegal && isLt2M;
}

function getgenApplyCode() {
  if (!form.value.id) {
    genApplyCode().then((res) => {
      form.value.applyCode = res.applyCode;
    })
  }
}
function getOrdPeople() {
  listAll().then((res) => {
    applyPeople.value = res.eaList;
  })
}
async function changePeole(val) {
  form.value.applyName = applyPeople.value.find((item) => item.id == val)?.name;
  const data = await elderArchiveinfo(val);
  const data4 = await region(data.elderArchiveDTO.livingAddrProvinceId);
  const data5 = await region(data.elderArchiveDTO.livingAddrCityId);
  const data6 = await region(data.elderArchiveDTO.livingAddrCountyId);
  const data7 = await region(data.elderArchiveDTO.livingAddrStreetId);
  livingCityList.value = data4.data;
  livingCountyList.value = data5.data;
  livingStreetList.value = data6.data;
  livingAddrCommunity.value = data7.data;
  form.value.livingConditions = data.elderArchiveDTO.livingConditions;
  form.value.telephone = data.elderArchiveDTO.telephone;
  form.value.sex = data.elderArchiveDTO.sex;
  form.value.idCard = data.elderArchiveDTO.idCard;
  form.value.birthDate = data.elderArchiveDTO.birthDate;
  form.value.age = data.elderArchiveDTO.age;
  form.value.livingAddrProvinceId = data.elderArchiveDTO.livingAddrProvinceId;
  form.value.livingAddrProvinceName =
    data.elderArchiveDTO.livingAddrProvinceName

  form.value.livingAddrCityId = data.elderArchiveDTO.livingAddrCityId;
  form.value.livingAddrCityName = data.elderArchiveDTO.livingAddrCityName;

  form.value.livingAddrCountyId = data.elderArchiveDTO.livingAddrCountyId;
  form.value.livingAddrCountyName = data.elderArchiveDTO.livingAddrCountyName;
  form.value.livingAddrStreetId = data.elderArchiveDTO.livingAddrStreetId;
  form.value.livingAddrStreetName = data.elderArchiveDTO.livingAddrStreetName;
  form.value.livingAddrCommunityId = data.elderArchiveDTO.livingAddrCommunityId;
  form.value.livingAddrCommunityName =
    data.elderArchiveDTO.livingAddrCommunityName
  form.value.livingDetailAddress = data.elderArchiveDTO.livingDetailAddress;
}
onMounted(async () => {
  // form.value=formData;
  if (formData.id) {
    const data4 = await region(formData.livingAddrProvinceId);
    const data5 = await region(formData.livingAddrCityId);
    const data6 = await region(formData.livingAddrCountyId);
    const data7 = await region(formData.livingAddrStreetId);

    livingCityList.value = data4.data;
    livingCountyList.value = data5.data;
    livingStreetList.value = data6.data;
    livingAddrCommunity.value = data7.data;
    form.value = formData;
    PositiveUrl.value = form.value.positiveUrl;
    imageUrl.value = form.value.negativeUrl;
    RegisterUrl.value = form.value.householdRegisterUrl;
  }
});

/** 查询岗位列表 */
function changelivingProvince(val) {
  form.value.livingAddrProvinceName = livingRegionList.value.find(
    (item) => item.areaCode == val,
  )?.name;
  livingCityList.value = [];
  form.value.livingAddrCityId = "";
  form.value.livingAddrCountyId = "";
  form.value.livingAddrStreetId = "";
  form.value.livingAddrCommunityId = '';
  livingCountyList.value = [];
  livingStreetList.value = [];
  region(val).then((res) => {
    livingCityList.value = res.data;
  })
}
function changelivingCity(val) {
  form.value.livingAddrCityName = livingCityList.value.find(
    (item) => item.areaCode == val,
  )?.name;
  form.value.livingAddrCountyId = "";
  form.value.livingAddrStreetId = "";
  form.value.livingAddrCommunityId = '';
  livingCountyList.value = [];
  livingStreetList.value = [];
  region(val).then((res) => {
    livingCountyList.value = res.data;
  })
}
function changelivingCounty(val) {
  form.value.livingAddrCountyName = livingCountyList.value.find(
    (item) => item.areaCode == val,
  )?.name;
  form.value.livingAddrStreetId = "";
  form.value.livingAddrCommunityId = "";
  livingStreetList.value = [];

  region(val).then((res) => {
    livingStreetList.value = res.data;
  })
}
function changelivingStreet(val) {
  form.value.livingAddrStreetName = livingStreetList.value.find(
    (item) => item.areaCode == val,
  )?.name;
  livingAddrCommunity.value = [];
  form.value.livingAddrCommunityId = "";
  region(val).then((res) => {
    livingAddrCommunity.value = res.data;
  })
}
function changelivingCommunity(val) {
  form.value.livingAddrCommunityName = livingAddrCommunity.value.find(
    (item) => item.areaCode == val,
  )?.name;
}
function getregion() {
  region(0).then((res) => {
    regionList.value = res.data;
    livingRegionList.value = res.data;
  })
}
getregion();
getgenApplyCode();
getOrdPeople();
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 280px;
  height: 180px;
  display: block;
}
</style>
<style>
.homened_container {
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 280px;
    height: 180px;
    text-align: center;
  }
}
</style>
